function [ A,B,C,D,E,F ] = FitEllipse( x,y )
%   The program for fitting ellipses to scattered data. x,y are vectors.
%   Using direct least squares method by minimizing the algebraic subject
%   to the constraint 4*a*c-b^2=1. [Andrew W.Fitzgibbon, 1996]
%%%
%               2*D'*D*a-2*lamda*C*a=0
%               a'*C*a=0
%               S*a=lamda*C*a
%               a'*C*a=1
%%%

%   Build design matrix
D=[x.*x ,x.*y,y.*y,x,y,ones(size(x))];
%   Build scatter matrix
S=D'*D;
%   Build 6X6 constraint matrix
C(6,6)=0;
C(1,3)=2;
C(2,2)=-1;
C(3,1)=2;
%   Solve eigensystem
[Vec,Val]=eig(S\C);
%   Find the positive eigenvalue
[PosRow,PosCol]=find(Val>0&~isinf(Val));
%   Get the engenvector and engenvalue lamda
U=Vec( : ,PosCol);
lamda=1/Val(PosRow,PosCol);
%   Get a
a=U.*sqrt(lamda/(U'*S*U));
%   Get the answer
A=a(1);
B=a(2);
C=a(3);
D=a(4);
E=a(5);
F=a(6);
end

